<?php

$totalCount = 0;
class importOldTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      new sfCommandOption('file', null, sfCommandOption::PARAMETER_REQUIRED, 'LUA File to convert', 'data/RPBot.lua'),
      // add your own options here
    ));

    $this->namespace        = 'raidpoints';
    $this->name             = 'import-old';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [import|INFO] task does things.
Call it with:

  [php symfony import|INFO]
EOF;
  }

  public function doLogSection($section, $message, $size = NULL, $style ='INFO')
  {
      global $totalCount;

      $q = Doctrine::getTable("DataImportStatus")
          ->createQuery()
          ->orderBy("date desc")
          ->limit(1);
      $r = $q->execute();

      $is = new DataImportStatus();
      $is->setDate(gmdate("Y-m-d H:i:s", time()));
      $is->setStatus($section);
      $is->setText($message);
      $is->setStatustotal($totalCount);
      if (isset($size))
      {
          $is->setStatusbar(0);
          $size = null;
      }
      elseif ($r->count() == 1)
      {
          $is->setStatusbar($r->getFirst()->getStatusbar()+1);
      }
      else
      {
          $is->setStatusbar(0);
      }
      $is->save();
      $this->logsection($section, $message, $size, $style);
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
    // add your code here
    //

    global $totalCount;

    $directory = scandir("data/import");
    if (count($directory) == 2)
    {
        $logT = "\t".date("F d, Y, g:i:s a", time());

        $this->doLogSection("Working", $logT, 0);
        $this->doLogSection("Working", "Opening Saved Variables file...");

        $lua = new LuaConverter();
        //copy($options["file"], "web/upload/".date("m.d.y H-i-s").".lua");
        $raiddata = ($lua->convert(utf8_decode(file_get_contents($options["file"]))));

        $this->doLogSection("Working", "Loading Saved Variables...");

        eval($raiddata);

        if (isset($rpDEBUGBotDB))
        {
            $arrayi = $rpDEBUGBotDB;
        }
        else
        {
            $arrayi = $rpBotDB;
        }

        $sortedraid = $arrayi["realm"];

        $this->doLogSection("Working", "Itterating Saved Variables...");
        foreach ( $sortedraid as $realm => $rdata )
        {
            foreach ( $rdata["player"] as $player => $pdata )
            {
                $query = Doctrine::getTable("Player")
                    ->createQuery()
                    ->where("name=?", strtolower(utf8_encode($pdata["name"])));
                $result = $query->execute();
                if ($result->count() == 0)
                {
                    $p = new Player();
                    $p->setFullname(utf8_encode($pdata["fullname"]));
                    $p->setName(utf8_encode($pdata["name"]));
                    $p->setAltid(1);
                    $p->setGuildedflag(1);

                    $query = Doctrine::getTable("PClass")
                        ->createQuery()
                        ->where("LOWER(name)=?", strtolower($pdata["class"]));
                    $result = $query->execute();
                    $c = $result->getFirst();
                    $p->setPClass($c);
                    //print_r($p->toArray());
                    try
                    {
                        $p->trySave();
                        $this->doLogSection("Working", "New Player: ".$p->getFullname());
                        $rdata["player"][$player]["id"] = $p->getId();
                    }
                    catch (exception $ex)
                    {

                    }
                }
            }
            global $totalCount;
            $totalCount = 0;
            foreach ( $rdata["raid"] as $raid => $value )
            {

                $query = Doctrine::getTable("Raid")
                    ->createQuery()
                    ->where("short=?", $raid)
                    ->andWhere("server=?", $realm);
                $result = $query->execute();
                $r = null;
                if ($result->count() > 0)
                    $r = $result->getFirst();
                else
                {
                    $r = new Raid();
                    $r->setName($raid);
                    $r->setShort($raid);
                    $r->setVisible(0);
                    $r->setServer($realm);
                }
                $actiont = 0;
                ksort($value);

                $this->doLogSection("Working", "Creating temporary cache for raid ".$raid."...");

                foreach ($value as $player => $data)
                {
                    ksort($data["recentactions"]);
                    $totalCount += count($data["recentactions"]);
                    $fp = fopen("data/import/". md5($realm."-".$raid."-".utf8_encode($player)) .".proc", "w");
                    fwrite($fp, serialize(array("raid" => $r->getId(), "player" => utf8_encode($player), "data" => $data)));
                    fclose($fp);
                }
            }
        }
        $directory = scandir("data/import");
    }

    if ($totalCount == 0)
    {
        $q = Doctrine::getTable("DataImportStatus")
            ->createQuery()
            ->orderBy("date desc")
            ->limit(1);
        $r = $q->execute();
        if ($r->count() == 1)
        {
            $totalCount = $r->getFirst()->getStatustotal();
        }
    }

    array_shift($directory);
    array_shift($directory);

    $this->doLogSection("Working", "Loading temporary cache...", 0);
    foreach ($directory as $file)
    {
        echo $file;
        if (substr($file, -4) == "proc")
        {
            $this->doLogSection("Working", "Executing task raidpoints:importPlayer ".$file);
            echo system(sfConfig::get('sf_root_dir')."/symfony raidpoints:importPlayer ".$file." ".$totalCount);
        }
    }
    //Doctrine::getTable("GuildHistory")->refresh();
    Doctrine::getTable("PlayerHistory")->updatePoints();
    $this->doLogSection("Finished", "Finished data import!");
    sleep(2);
    $is = new DataImportStatus();
    $is->setDate((time()));
    $is->setStatus("Ready");
    $is->setText("Ready for next import.");
    $is->setStatustotal(0);
    $is->setStatusbar(0);
    $is->save();
    system(sfConfig::get('sf_root_dir')."/symfony raidpoints:updatepoints");

    /*
    $r = Doctrine::getTable("History")->getLastLog('2009-07-05 17:01:59', 10, 1);
    $r = $r->getFirst();

    $r = Doctrine::getTable("PlayerHistory")->updatePoints(2, 1);

    $newHistory = new History();
    $newHistory->setDate('2009-07-05 17:01:59');
    $newHistory->setActiondate('2009-07-05 17:02:51');
    $newHistory->setSavedate($newHistory->getActiondate());
    $newHistory->setLogdate(time());
    $newHistory->setLogcomment(' ');
    $newHistory->setComment(' ');
    $newHistory->setItemid(0);
    $newHistory->setOfficerid(0);
    $newHistory->setPlayerid(10);
    $newHistory->setRaidid(1);
    $newHistory->setReasonid(831);
    $newHistory->setTtype('I');
    $newHistory->setValue('0');
    $newHistory->setWaitlistflag(0);
    $newHistory->setZoneid(0);
    $newHistory->setAaction("D");
    $newHistory->save();

    $this->logsection("do-nothing", "I did nothing...");
    //print_r($r->getAction());
    */


  }
}
